//
//  HMGroupChatViewController.m
//  HMWeChat
//
//  Created by apple on 2017/5/13.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMGroupChatViewController.h"

static NSString *sendID = @"send";
static NSString *recvID = @"recv";
static NSString *sendImgID = @"sendImg";
static NSString *recvImgID = @"recvImg";

@interface HMGroupChatViewController ()<UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

//查询结果控制器  实时监听消息变化(发出&收到),也需要使用查询结果控制器
@property (nonatomic, strong) NSFetchedResultsController *fetchController;
//真实JID查询控制器  监听占有者表的变化(聊天室人员的变化)
@property (nonatomic, strong) NSFetchedResultsController *realJIDFetchController;

@property (nonatomic, strong) NSArray <XMPPRoomMessageCoreDataStorageObject *> *messages;
//真实JID缓存
@property (nonatomic, strong) NSMutableDictionary *realJIDCache;

@end

@implementation HMGroupChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //设置预估行高
    self.tableView.estimatedRowHeight = 200;
    //自动计算行高
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    //刷新真实JID
    [self refreshRealJID];
    //执行刷新 需要在获取到真实JID之后再刷新界面
    [self refreshData];
}


- (void)refreshData{
    
    BOOL success = [self.fetchController performFetch:nil];
    if (success) {
        self.messages = self.fetchController.fetchedObjects;
        [self.tableView reloadData];
    }
    //执行滚动
    if (self.messages.count > 0) {
        
        dispatch_async(dispatch_get_main_queue(), ^{ //为了避免没有遍历完数据就执行滚动,将执行滚动的操作添加到主队列的异步任务中,保证在执行到当前任务时,主线程的任务已经全部清空
            
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        });
        
    }
}

//刷新真实JID
- (void)refreshRealJID{

    BOOL success = [self.realJIDFetchController performFetch:nil];
    if (success) {
        //获取记录
        for (XMPPRoomOccupantCoreDataStorageObject *occupantCDO in self.realJIDFetchController.fetchedObjects) {
            
            //记录虚拟JID和真实JID的关系
            [self.realJIDCache setValue:occupantCDO.realJID forKey:occupantCDO.jidStr];
        }
    }
}

- (IBAction)clickInviteFriendItem:(id)sender {
    
    //使用房间模块执行邀请
    XMPPRoom *room = [HMXMPPRoomManager sharedManager].roomCache[self.roomJID.user];
    [room inviteUser:[XMPPJID jidWithUser:@"lisi" domain:@"im.itcast.cn" resource:nil] withMessage:@"快来,同学们都在这呢~"];
}



#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    //封装message节
    XMPPMessage *message = [XMPPMessage messageWithType:@"groupchat" to:self.roomJID];
    [message addBody:textField.text];
    
    //发送消息
    [[HMXMPPManager sharedManager].xmppStream sendElement:message];
    
    textField.text = nil;

    return YES;
}

#pragma mark - NSFetchedResultsControllerDelegate

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
    
    if (controller == self.fetchController) { //消息表变化
        
        [self refreshData];
        
    } else { //群成员表变化
    
        [self refreshRealJID];
    }
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.messages.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell;
    
    XMPPRoomMessageCoreDataStorageObject *msgCDO = self.messages[indexPath.row];
    
    //区分不同的类型
    switch ([msgCDO.message.subject intValue]) {
        case HMXMPPMsgTypeTXT: //文本
        {
            //区分发出/接收
            if (msgCDO.isFromMe) { //发出
                
                cell = [tableView dequeueReusableCellWithIdentifier:sendID forIndexPath:indexPath];
                //显示自己的头像
                UIImageView *imgV = [cell viewWithTag:1001];
                imgV.image = [UIImage imageWithData:[HMXMPPManager sharedManager].xmppvCard.myvCardTemp.photo];
                
            }else { //接收
                
                cell = [tableView dequeueReusableCellWithIdentifier:recvID forIndexPath:indexPath];
                
                
                //显示群成员的头像  必须获取群成员的真实JID(通过虚拟JID到Occupant表中去获取真实JID)
                UIImageView *imgV = [cell viewWithTag:1001];
                imgV.image = [UIImage imageWithData:[[HMXMPPManager sharedManager].xmppAvatar photoDataForJID:self.realJIDCache[msgCDO.jidStr]]];
                
            }
            //设置数据
            UILabel *contentLabel = [cell viewWithTag:1002];
            contentLabel.text = msgCDO.message.body;
        }
            break;
            
        default:
            break;
    }
    
    
    
    return cell;
}


#pragma mark - 懒加载

- (NSFetchedResultsController *)fetchController{
    
    if (_fetchController == nil) {
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPRoomMessageCoreDataStorageObject" inManagedObjectContext:[XMPPRoomCoreDataStorage sharedInstance].mainThreadManagedObjectContext];
        [fetchRequest setEntity:entity];
        //设置过滤条件  消息必须是当前房间的
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"roomJIDStr = %@", self.roomJID.bare];
        [fetchRequest setPredicate:predicate];
        // 设置排序   时间升序
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"localTimestamp" ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        _fetchController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[XMPPRoomCoreDataStorage sharedInstance].mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
        
        _fetchController.delegate = self;
    }
    return _fetchController;
}


- (NSFetchedResultsController *)realJIDFetchController{
    if (_realJIDFetchController == nil) {
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPRoomOccupantCoreDataStorageObject" inManagedObjectContext:[XMPPRoomCoreDataStorage sharedInstance].mainThreadManagedObjectContext];
        [fetchRequest setEntity:entity];
        // 设置谓词 查询当前聊天室中的jid对应关系
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"roomJIDStr = %@", self.roomJID.bare];
        [fetchRequest setPredicate:predicate];
        //必须设置排序
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"jidStr" ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        _realJIDFetchController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[XMPPRoomCoreDataStorage sharedInstance].mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
        
        _realJIDFetchController.delegate = self;
    }
    return _realJIDFetchController;
}

- (NSMutableDictionary *)realJIDCache{
    
    if (_realJIDCache == nil) {
        _realJIDCache = [[NSMutableDictionary alloc] init];
    }
    return _realJIDCache;
}


@end
